import './style.less'
import { useEffect, useRef, useState } from 'react'
import { Button, Select, Descriptions, Tag, List, message, Space } from 'antd';
import { useSelector } from 'react-redux'
import qimg from '@/assets/q.png'

function Install() {
  useEffect(() => {
    
    syncPkgs()
    electronAPI.installApk(onInstallApk)
  }, [])

  const [files, setFiles] = useState([]); // 选中的apk列表
  const device = useSelector((state) => state.device)


  const syncPkgs = async ()=>{
    const res = await electronAPI.getPkgs(device['ro.serialno']['value'], 3);
    console.log(res);
  }

  /**
  * 监听安装进度
  * @param {*} value 
  */
  const filesRef = useRef([]);
  const onInstallApk = (value) => {
    filesRef.current.forEach((file,index) => {
      if(file.path===value.path){
        filesRef.current[index] = {...file, ...value}
      }
    });
    setFiles([...filesRef.current])
  }

  /**
    * 打开上传文件窗口
    */
  const onSelectFile = async () => {
    let res = await electronAPI.openFileDialog(['apk'], true);
    res = res.map(item=>({path: item, status: '未开始'}))
    filesRef.current = res;
    setFiles(res)
  }

  const removeFiles = (filePath) => {
    const index = files.findIndex(item => item.path === filePath);
    files.splice(index, 1);
    setFiles([...files])
    filesRef.current = [...files];
  }

  return (
    <div className='pkg'>
      {device ? 
        <List
          className='mt-4'
          header={<div className='flex items-center justify-between'>
            <div className='text-green-700 font-bold text-base'>待安装列表</div>
            <Space>
              <Button onClick={onSelectFile}>请选择上传文件</Button>
              <Button disabled={files.length===0} onClick={()=>{electronAPI.installApk(device['ro.serialno']['value'], files.map(file=>file.path))}} type="primary">开始安装</Button>
            </Space>
          </div>}
          bordered
          dataSource={files}
          renderItem={(item) => (
            <List.Item actions={[<a className='text-blue-400' key={item.path} onClick={() => { removeFiles(item.path) }}>移除</a>]}>
              <div className='flex items-center'>
                <div>状态：{item.status}</div>
                <div className='ml-8'>{item.path}</div>
              </div>
            </List.Item>
          )}
        />:<div className='need-device mt-28'>
           
            <span>设备呢？</span>
            <img src={qimg} alt="" />
        </div>}
    </div>
  )
}

export default Install;
